# -*- coding: utf-8 -*-

from openerp import models, fields, api, _
from openerp.exceptions import Warning

class project_make_sale(models.TransientModel):
    """ Make sale  order for project """
    _name = "sale.project.make.sale"

    _description = "Make sales"

    partner_id = fields.Many2one('res.partner', string='Customer Id', required=True, domain=[('customer','=',True)],
        help="")
    name = fields.Char(string=u'合同名称', required=True)

    @api.multi
    def makeOrder(self):
        """
        This function  create Quotation on given case.
        @param self: The object pointer
        @return: Dictionary value of created sales order.
        """
        print('makeOrder===========')
        case_obj = self.env['sale.project']
        account_obj = self.env['account.analytic.account']
        partner_obj = self.env['res.partner']
        data = self._context.get('active_ids', []) or []

        print(data)
        for make in self:
            partner = make.partner_id
            print(partner)
            partner_addr = partner.address_get(['default', 'invoice', 'delivery', 'contact'])
            print(partner_addr)
            pricelist = partner.property_product_pricelist.id
            fpos = partner.property_account_position and partner.property_account_position.id or False
            payment_term = partner.property_payment_term and partner.property_payment_term.id or False
            new_ids = []
            for case in self.env['sale.project'].browse(data):
                case_obj = self.env['sale.project']
                # if not partner and case.partner_id:
                #     partner = case.partner_id
                #     fpos = partner.property_account_position and partner.property_account_position.id or False
                #     payment_term = partner.property_payment_term and partner.property_payment_term.id or False
                #     partner_addr = partner.address_get(['default', 'invoice', 'delivery', 'contact'])
                #     print(partner_addr)
                #     print(partner_addr['invoice'])
                #     pricelist = partner.property_product_pricelist.id
                # if False in partner_addr.values():
                #     raise Warning(_('Insufficient Data!'), _('No address(es) defined for this customer.'))

                # vals = {
                #     'origin': _('Project: %s') % str(case.id),
                #     'partner_id': partner.id,
                #     'pricelist_id': pricelist,
                #     'partner_invoice_id': partner_addr['invoice'],
                #     'partner_shipping_id': partner_addr['delivery'],
                #     'date_order': fields.Date.context_today(self),
                #     'fiscal_position': fpos,
                #     'payment_term':payment_term,
                #     'project': case.id,
                # }
                print('========',self.name)
                vals = {
                    'name': self.name
                }

                # if partner.id:
                #     vals['user_id'] = partner.user_id and partner.user_id.id or self.env.user.id
                # print('create order with:',vals)
                # new_id = account_obj.create(vals)
                # print(new_id)
                # sale_order = sale_obj.browse(new_id)
                # case_obj.write({'ref': 'sale.order,%s' % new_id})
                # new_ids.append(new_id)
                # message = _("Project has been <b>converted</b> to the quotation <em>%s</em>.") % (sale_order.name)
                # case.message_post(body=message)
            
            if not new_ids:
                return {'type': 'ir.actions.act_window_close'}
            if len(new_ids)<=1:
                value = {
                    'domain': str([('id', 'in', new_ids)]),
                    'view_type': 'form',
                    'view_mode': 'form',
                    'res_model': 'account.analytic.account',
                    'view_id': False,
                    'type': 'ir.actions.act_window',
                    'name' : _('Quotation'),
                    'res_id': new_ids and new_ids[0]
                }
            else:
                value = {
                    'domain': str([('id', 'in', new_ids)]),
                    'view_type': 'form',
                    'view_mode': 'tree,form',
                    'res_model': 'account.analytic.account',
                    'view_id': False,
                    'type': 'ir.actions.act_window',
                    'name' : _('Project'),
                    'res_id': new_ids
                }
            return value

    @api.multi
    def _selectPartner(self):
        """
        This function gets default value for partner_id field.
        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks,
        @param context: A standard dictionary for contextual values
        @return: default value of partner_id field.
        """

        active_id = self._context.get('active_id', False) or False
        if not active_id:
            return False

        lead = self.env['sale.project'].read([active_id], ['partner_id'])[0]
        return lead['partner_id'][0] if lead['partner_id'] else False


# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
